<template>
  <el-dialog
    v-model="dialogVisible"
    width="800px"
    :before-close="handleClose"
    destroy-on-close
    class="menu-dialog"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
  >
    <!-- 弹窗头部 -->
    <template #header>
      <div class="dialog-header">
        <div class="header-content">
          <div class="header-icon">
            <el-icon :size="32">
              <Menu />
            </el-icon>
          </div>
          <div class="header-text">
            <h3 class="header-title">{{ title }}</h3>
            <p class="header-subtitle">配置菜单的基本信息和权限设置</p>
          </div>
        </div>
      </div>
    </template>

    <!-- 弹窗主体 -->
    <div class="dialog-body">
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
        class="menu-form"
      >
                 <!-- 基本信息 -->
         <div class="form-section">
           <div class="section-header">
             <el-icon class="section-icon">
               <InfoFilled />
             </el-icon>
             <span class="section-title">基本信息</span>
           </div>
           
                       <div class="form-grid">
              <el-form-item label="菜单名称" prop="name" class="form-item-enhanced">
                <el-input
                  v-model="form.name"
                  placeholder="请输入菜单名称，如：menu-manage"
                  clearable
                />
              </el-form-item>

              <el-form-item label="菜单路径" prop="path" class="form-item-enhanced">
                <el-input
                  v-model="form.path"
                  placeholder="请输入菜单路径，如：/menu-manage"
                  clearable
                />
              </el-form-item>

              <el-form-item label="菜单图标" prop="meta.icon" class="form-item-enhanced">
                <el-input
                  v-model="form.meta.icon"
                  placeholder="请输入图标名称，如：menu"
                  clearable
                />
              </el-form-item>

                             <el-form-item label="显示名称" prop="meta.locale" class="form-item-enhanced">
                 <el-input
                   v-model="form.meta.locale"
                   placeholder="请输入显示名称，如：菜单管理"
                   clearable
                 />
               </el-form-item>

               <el-form-item label="排序" prop="meta.order" class="form-item-enhanced">
                 <el-input-number
                   v-model="form.meta.order"
                   :min="0"
                   :max="999"
                   placeholder="请输入排序值"
                   style="width: 100%"
                 />
               </el-form-item>
            </div>
         </div>

         
      </el-form>
    </div>

    <!-- 弹窗底部 -->
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose" class="cancel-btn">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading" class="submit-btn">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import type { MenuItem, CreateMenuRequest } from '@/api/sys/menu.api'
import { 
  Menu, 
  InfoFilled, 
  Setting, 
  Lock, 
  Operation, 
  CircleCheck, 
  CircleClose 
} from '@element-plus/icons-vue'

interface Props {
  visible: boolean
  title: string
  formData: Partial<MenuItem>
  menuTree: MenuItem[]
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'submit', data: CreateMenuRequest): void
  (e: 'cancel'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const formRef = ref<FormInstance>()
const loading = ref(false)

// 表单数据
const form = ref({
  name: '',
  path: '',
  meta: {
    icon: '',
    locale: '',
    requires_auth: true,
    order: 0
  }
})

// 表单验证规则
const rules: FormRules = {
  name: [
    { required: true, message: '请输入菜单名称', trigger: 'blur' },
    { min: 2, max: 50, message: '菜单名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  path: [
    { required: true, message: '请输入菜单路径', trigger: 'blur' },
    { pattern: /^\/[a-zA-Z0-9\/-]*$/, message: '路径格式不正确，应以/开头', trigger: 'blur' }
  ],
  'meta.icon': [
    { required: true, message: '请输入菜单图标', trigger: 'blur' }
  ],
  'meta.locale': [
    { required: true, message: '请输入显示名称', trigger: 'blur' }
  ],
  'meta.order': [
    { type: 'number', min: 0, max: 999, message: '排序值应在 0 到 999 之间', trigger: 'blur' }
  ]
}

// 树形选择器配置
const treeProps = {
  children: 'children',
  label: 'name',
  value: 'id'
}

// 常用权限标识
const commonPermissions = [
  'menu:view',
  'menu:add',
  'menu:edit',
  'menu:delete',
  'user:view',
  'user:add',
  'user:edit',
  'user:delete',
  'role:view',
  'role:add',
  'role:edit',
  'role:delete',
  'permission:view',
  'permission:assign'
]

// 计算属性
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 菜单树选项（排除当前编辑的菜单及其子菜单）
const menuTreeOptions = computed(() => {
  if (!props.formData.id) {
    return props.menuTree
  }
  
  // 过滤掉当前菜单及其子菜单
  const filterTree = (items: MenuItem[], excludeId: number): MenuItem[] => {
    return items
      .filter(item => item.id !== excludeId)
      .map(item => ({
        ...item,
        children: item.children ? filterTree(item.children, excludeId) : undefined
      }))
      .filter(item => item.children === undefined || item.children.length > 0)
  }
  
  return filterTree(props.menuTree, props.formData.id)
})

// 监听表单数据变化
watch(
  () => props.formData,
  (newData) => {
    if (newData && Object.keys(newData).length > 0) {
      form.value = {
        name: newData.name || '',
        path: newData.path || '',
        meta: {
          icon: newData.meta?.icon || '',
          locale: newData.meta?.locale || '',
          requires_auth: newData.meta?.requires_auth ?? true,
          order: newData.meta?.order || 0
        }
      }
    } else {
      // 重置表单
      form.value = {
        name: '',
        path: '',
        meta: {
          icon: '',
          locale: '',
          requires_auth: true,
          order: 0
        }
      }
    }
  },
  { immediate: true, deep: true }
)

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    loading.value = true
    
         const submitData = {
       name: form.value.name,
       path: form.value.path,
       meta: form.value.meta
     }
    
    emit('submit', submitData)
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    loading.value = false
  }
}

// 关闭弹窗
const handleClose = () => {
  emit('update:visible', false)
  emit('cancel')
}
</script>

<style scoped>
/* 弹窗整体样式 */
.menu-dialog :deep(.el-dialog) {
  border-radius: 16px;
  overflow: hidden;
  background: #ffffff;
  height: 80vh;
  display: flex;
  flex-direction: column;
}

.menu-dialog :deep(.el-dialog__header) {
  padding: 0;
  margin: 0;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.menu-dialog :deep(.el-dialog__body) {
  padding: 0;
  flex: 1;
  overflow-y: auto;
 height:600px
}

.menu-dialog :deep(.el-dialog__footer) {
  padding: 0;
}

.menu-dialog :deep(.el-dialog__headerbtn) {
  top: 20px;
  right: 20px;
  width: 40px;
  height: 40px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  transition: all 0.3s ease;
}

.menu-dialog :deep(.el-dialog__headerbtn:hover) {
  background: rgba(255, 255, 255, 0.3);
  transform: scale(1.1);
}

.menu-dialog :deep(.el-dialog__headerbtn .el-dialog__close) {
  font-size: 18px;
  font-weight: bold;
}

/* 弹窗头部样式 */
.dialog-header {
  padding: 20px;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-icon {
  font-size: 32px;
}

.header-text {
  flex: 1;
}

.header-title {
  margin: 0 0 4px 0;
  font-size: 20px;
  font-weight: 600;
}

.header-subtitle {
  margin: 0;
  font-size: 14px;
}

/* 弹窗主体样式 */
.dialog-body {
  background: #f8fafc;
}

.menu-form {
  max-width: 100%;
}

/* 表单分组样式 */
.form-section {
  margin-bottom: 28px;
  background: white;
  border-radius: 16px;
  padding: 28px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  border: 1px solid #f1f5f9;
  position: relative;
}

.form-section:last-child {
  margin-bottom: 0;
}

.section-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 2px solid #f1f5f9;
}

.section-icon {
  font-size: 20px;
  color: #667eea;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #374151;
}

/* 表单网格布局 */
.form-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 24px;
  align-items: start;
}

.form-grid .el-form-item {
  margin-bottom: 0;
}

/* 单列表单项 */
.form-single {
  grid-column: 1 / -1;
}

/* 增强的表单项样式 */
.form-item-enhanced {
  margin-bottom: 24px;
}

.form-item-enhanced :deep(.el-form-item__label) {
  font-weight: 600;
  color: #374151;
  font-size: 14px;
  margin-bottom: 8px;
  line-height: 1.5;
}

.form-item-enhanced :deep(.el-input) {
  height: 44px;
}

.form-item-enhanced :deep(.el-input__wrapper) {
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
  border: 1px solid #e2e8f0;
  transition: all 0.3s ease;
  padding: 0 16px;
  height: 44px;
}

.form-item-enhanced :deep(.el-input__wrapper:hover) {
  border-color: #667eea;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.1);
}

.form-item-enhanced :deep(.el-input__wrapper.is-focus) {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.form-item-enhanced :deep(.el-select .el-input__wrapper) {
  border-radius: 12px;
}

.form-item-enhanced :deep(.el-select) {
  width: 100%;
}

.form-item-enhanced :deep(.el-input__inner) {
  height: 42px;
  line-height: 42px;
}

.form-item-enhanced :deep(.el-tree-select) {
  width: 100%;
}

.form-item-enhanced :deep(.el-tree-select .el-input__wrapper) {
  border-radius: 12px;
}

.form-item-enhanced :deep(.el-input-number .el-input__wrapper) {
  border-radius: 12px;
}

/* 单选按钮组样式 */
.form-item-enhanced :deep(.el-radio-group) {
  display: flex;
  gap: 20px;
}

.form-item-enhanced :deep(.el-radio) {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-right: 0;
}

.form-item-enhanced :deep(.el-radio__label) {
  display: flex;
  align-items: center;
  gap: 6px;
  font-weight: 500;
}

/* 权限提示样式 */
.permission-tips {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 8px;
  padding: 8px 12px;
  background: #f0f9ff;
  border: 1px solid #bae6fd;
  border-radius: 8px;
  font-size: 12px;
  color: #0369a1;
}

.permission-tips .el-icon {
  font-size: 14px;
  color: #0ea5e9;
}

/* 弹窗底部样式 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 16px;
  padding: 24px 32px;
  background: #f8fafc;
  border-top: 1px solid #e5e7eb;
}

.cancel-btn {
  padding: 12px 24px;
  border-radius: 8px;
  font-weight: 600;
  background: #f1f5f9;
  border: 1px solid #d1d5db;
  color: #6b7280;
  transition: all 0.3s ease;
}

.cancel-btn:hover {
  background: #e5e7eb;
  border-color: #9ca3af;
  transform: translateY(-1px);
}

.submit-btn {
  padding: 12px 24px;
  border-radius: 8px;
  font-weight: 600;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  color: white;
  transition: all 0.3s ease;
}

.submit-btn:hover {
  background: linear-gradient(135deg, #5a67d8 0%, #6b46c1 100%);
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}
:deep(.el-dialog__body){
    height:600px;
    overflow-y: auto;

}
/* 响应式设计 */
@media (max-width: 768px) {
  .menu-dialog :deep(.el-dialog) {
    width: 95% !important;
    margin: 5vh auto;
  }

  .dialog-header {
    padding: 20px;
  }

  .header-title {
    font-size: 18px;
  }

  .dialog-body {
    padding: 20px;
  }

  .form-section {
    padding: 20px;
    margin-bottom: 20px;
  }

  .form-grid {
    grid-template-columns: 1fr;
    gap: 16px;
  }

  .dialog-footer {
    padding: 20px;
    flex-direction: column;
  }

  .cancel-btn,
  .submit-btn {
    width: 100%;
  }
}

@media (max-width: 1024px) {
  .menu-dialog :deep(.el-dialog) {
    width: 90% !important;
  }

  .form-grid {
    gap: 20px;
  }
}
</style>
